package jp.co.technotree.common.dao;

import jp.co.technotree.common.util.DBGLog;
import jp.co.technotree.exception.StatementParameterException;


public class StatementCreator {
	private static String CLASSNAME=StatementParser.class.getName();

	public StatementCreator(){
		
	}

	/**
	 * 
	 * @param preStmt
	 * @param tableName
	 * @param params
	 * @throws StatementParameterException
	 */
	public String insert(String tableName,StatementParameters params) throws StatementParameterException{
		String METHODNAME = "setParameters";
		DBGLog.fwdebug(CLASSNAME,METHODNAME,"START");
		int i;
		String sql = "";
		
		// --------------------------------------------------
		// SQL作成
		sql = "insert into "+tableName+" (";
		for ( i=0; i<params.length(); i++ ){
			StatementParameters.StatementParameter param = params.getParameter(i);
			if ( param == null ){
				StatementParameterException exception = new StatementParameterException("項目["+param.getName()+"]に値が設定されていません。");
				throw exception;
			}
			if ( i != 0 ) sql += ",";
			sql += param.getName()+"\n";
		}
		sql += ") values (";
		for ( i=0; i<params.length(); i++ ){
			StatementParameters.StatementParameter param = params.getParameter(i);
			if ( i != 0 ) sql += ",";
			if ( param.getType() == params.TYPE_STRINGFORMAT ){
				String values[] = (String[])param.getValue();
				String fmt = values[0];
				
				int idx = fmt.indexOf('?');
				if ( idx != -1 ){
					String v1 = fmt.substring(0, idx);
					String v2 = fmt.substring(idx+1, fmt.length());
					
					sql += v1+"{:"+param.getName()+"}"+v2+"\n";
				}else{
					StatementParameterException exception = new StatementParameterException("項目定義エラー["+param.getName()+"]フォーマット異常");
					throw exception;
				}
			}else{
				sql += "{:"+param.getName()+"}\n";
			}
		}
		sql += ")\n";
		DBGLog.fwdebug(CLASSNAME,METHODNAME,"SQL:"+sql);
		
		DBGLog.fwdebug(CLASSNAME,METHODNAME,"END");
		
		return sql;
		
	}

}
